/**
 * Copyright 2014 @ z3q.net.
 * name :
 * author : jarryliu
 * date : 2013-12-12 16:52
 * description :
 * history :
 */

package seller

import (
    "dhfshop/models"
	"strings"
	"errors"
	"time"
	"dhfshop/models/consts"
	"github.com/astaxie/beego/orm"
)

//合作分销关系
type Cooperation struct {
	CooperateId     int64    `orm:"column(cooperate_id);pk;auto" json:"cooperate_id" form:"cooperate_id"` //合作关系ID 
	DistributorId   int64  `orm:"column(distributor_id)" json:"distributor_id" form:"distributor_id"`   //分销商ID
	DistributorNick string `orm:"column(distributor_nick)" json:"distributor_nick" form:"distributor_nick"` //分销商nick
	ProductLine     string `orm:"column(product_line)" json:"product_line" form:"product_line"` //授权产品线, 逗号分隔的字符串，如：123,123
	ProductLineName string `orm:"column(product_line_name)" json:"product_line_name" form:"product_line_name"` //产品线一,产品线二,产品线三	 授权产品线名称，和product_line中的值按序对应
	GradeId         int    `orm:"column(grade_id)" json:"grade_id" form:"grade_id"`             //等级ID
	TradeType       string `orm:"column(trade_type)" json:"trade_type" form:"trade_type"`    //分销方式： AGENT(代销) 、DEALER(经销)
	AuthPayway      string `orm:"column(auth_payway)" json:"auth_payway" form:"auth_payway"` //供应商授权的支付方式：ALIPAY(支付宝)、OFFPREPAY(预付款)、OFFTRANSFER(转帐)、OFFSETTLEMENT(后期结算)
	SupplierId      int64   `orm:"column(supplier_id)" json:"supplier_id" form:"supplier_id"`   //供应商ID
	SupplierNick    string  `orm:"column(supplier_nick)" json:"supplier_nick" form:"supplier_nick"` //供应商NICK
	StartDate       time.Time  `orm:"column(start_date);type(datetime);null" json:"-" form:"-"` /* 合作起始时间 */
    StartDateStr    string     `orm:"-" json:"start_date" form:"start_date"`
	EndDate         time.Time  `orm:"column(end_date);type(datetime);null" json:"-" form:"-"`   /* 合作终止时间 */
	EndDateStr      string     `orm:"-" json:"end_date" form:"end_date"`
	StatusId        int32     `orm:"column(status_id);index;default(0)" json:"status_id" form:"status_id"` //状态可选值：0,1,2
	CreatedAt       time.Time   `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`   /* 创建时间 */
	CreatedAtStr    string      `orm:"-" json:"created_at" form:"-"`
	UpdatedAt       time.Time   `orm:"auto_now;column(updated_at);type(datetime)" json:"-" form:"-"` 
	UpdatedAtStr    string      `orm:"-" json:"updated_at" form:"-"`
	//
	SupplierAgree        bool       `orm:"column(supplier_agree);default(false)" json:"supplier_agree" form:"supplier_agree"` //供应商审批
	SupplierAgreeTime    time.Time  `orm:"column(supplier_agree_time);type(datetime);null" json:"-" form:"-"` 
	SupplierAgreeTimeStr string     `orm:"-" json:"supplier_agree_time" form:"supplier_agree_time"`
	SellerAgree          bool       `orm:"column(seller_agree);default(false)" json:"seller_agree" form:"seller_agree"` //分销商审批
	SellerAgreeTime      time.Time  `orm:"column(seller_agree_time);type(datetime);null" json:"-" form:"-"`
    SellerAgreeTimeStr   string     `orm:"-" json:"seller_agree_time" form:"seller_agree_time"`	
}

func (u *Cooperation) TableUnique() [][]string {
	return [][]string{
		[]string{"DistributorId", "SupplierId"},
	}
}

func init() {
    orm.RegisterModel(new(Cooperation))   
}

func AddCooperation(m *Cooperation) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetCooperationById(id int64) (v *Cooperation, err error) {
	o := models.GetDefaultDB()
	v = &Cooperation{CooperateId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllCooperations(query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*Cooperation, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Cooperation))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Cooperation
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, operation := range lists {
			operation.CreatedAtStr = operation.CreatedAt.Format(consts.DATETIME_FORMAT)
			operation.UpdatedAtStr = operation.UpdatedAt.Format(consts.DATETIME_FORMAT)
			operation.StartDateStr = operation.StartDate.Format(consts.DATETIME_FORMAT)
			operation.EndDateStr = operation.EndDate.Format(consts.DATETIME_FORMAT)
			operation.SupplierAgreeTimeStr = operation.SupplierAgreeTime.Format(consts.DATETIME_FORMAT)
			operation.SellerAgreeTimeStr = operation.SellerAgreeTime.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateCooperationById(m *Cooperation, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := Cooperation{CooperateId: m.CooperateId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

func DeleteCooperation(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Cooperation{CooperateId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
